from http.client import responses
from starlette.responses import JSONResponse
from app.extensions import get_db
from app.models.Clas import Clas
from app.services.StudentService import StudentService
from fastapi import APIRouter
from app.schames.Student import StudentSchema, StudentCreate

student_route = APIRouter(prefix="/student", tags=["学生管理"])

@student_route.get("/", summary="搜索学生")
def get_by_keyword(keyword:str = ""):
    with get_db() as db: # 链接数据库
        # 创建service对象并调用服务
        svc = StudentService(db)
        response = svc.get_by_keyword(keyword)
        return JSONResponse(
            content={
                "data": [StudentSchema.model_validate(item).model_dump() for item in response["data"]],   # ORM转为dict
                "message": response["message"]
            },
            status_code=response["code"]
        )

def add_student(clas_id, name, gender):
    with get_db() as db:
        svc = StudentService(db)
        response = svc.add_student(clas_id, name, gender)
        return  response

def update_student(stu_id, new_name, new_gender, new_clas_id):
     with get_db() as db:
         svc = StudentService(db)
         response = svc.update_student(stu_id, new_name, new_gender, new_clas_id)
         return  response

@student_route.delete("/{id}", summary="删除学生" )
def delete_student(id:int):
    with get_db() as db:
        svc = StudentService(db)
        response = svc.delete_student(id)
        return JSONResponse(
           content={
               "data":response["data"],
               "message": response["message"]
           },
            status_code= response["code"]
        )

@student_route.post("/", summary="增加学生")
def add_student(stu: StudentCreate):
    with get_db() as db:
        svc = StudentService(db)
        response = svc.add_student(stu.clas_id, stu.name, stu.gender)
        return JSONResponse(
            content={
                "data": response["data"],
                "message": response["message"]
            },
            status_code=response["code"]
        )


@student_route.put("/", summary="修改学生")
def update_student(stu_id, stu: StudentCreate):
    with get_db() as db:
        svc = StudentService(db)
        response = svc.update_student(stu_id, stu.name, stu.gender, stu.clas_id)
        return JSONResponse(
            content={
                "data": response["data"],
                "message": response["message"]
            },
            status_code=response["code"]
        )
